/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.config;

import com.moyu.sql.response.SuccessResponseData;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

import java.util.concurrent.atomic.AtomicReference;

@Configuration
public class DynamicRouterConfig {
    private final AtomicReference<RouterFunction<ServerResponse>> routerRef;
    private final ApplicationEventPublisher eventPublisher; // 用于触发路由刷新

    public DynamicRouterConfig(ApplicationEventPublisher eventPublisher) {
        this.eventPublisher = eventPublisher;
        routerRef = new AtomicReference<>();
    }

    @Bean
    public RouterFunction<ServerResponse> dynamicRouter() {
        routerRef.set(RouterFunctions.route()
                .GET("/health", request -> ServerResponse.ok().body(new SuccessResponseData("OK")))
                .build()); // 初始空路由
        return routerRef.get();
    }

    /**
     * 动态更新路由
     */
    public void updateRouter(RouterFunction<ServerResponse> newRouter) {
        // 直接合并两个RouterFunction
        routerRef.updateAndGet(newRouter::and);
        eventPublisher.publishEvent(new RouterRefreshedEvent(this)); // 触发路由刷新事件
    }

    public RouterFunction<?> getCurrentRouter() {
        return routerRef.get();
    }
}

